package com.crm.interceptor;


import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.crm.common.utils.ThreadLocalUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.Map;

@Component
@Slf4j
public class MyMetaObjectHandler implements MetaObjectHandler {

    @Override
    public void insertFill(MetaObject metaObject) {
        this.strictInsertFill(metaObject, "createTime", Date.class, new Date());
        this.strictInsertFill(metaObject, "createBy", String.class, loadUserId()+"");
        this.setFieldValByName("updateTime",new Date(),metaObject);
        this.setFieldValByName("updateBy", loadUserId()+"",metaObject);
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        this.setFieldValByName("updateTime",new Date(),metaObject);
        this.setFieldValByName("updateBy", loadUserId()+"",metaObject);
    }

    /**
     * 获取当前登录人的ID
     * @return
     */
    public static Long loadUserId(){
        //获取当前登录人的id
        try {
            return ThreadLocalUtil.getUserId();
        }catch (Exception e){
            log.info("没有用户");
            return 1L;
        }
    }
}
